<?php
class Mozg_ExceptionHandler extends Mozg_Env_Base
{
	protected $_moduleName = '';
	
    protected $_detector;

    public function __construct($protName, $envName)
    {
    	parent::__construct($protName, $envName);
    	
        $this->_detector = new Mozg_Detector($this);
		list($this->_moduleName) = $this->_detector->last();
    }
	
	public function Handle(Exception $e)
	{
		$this->CleanBuffers();
		
		$class = get_class($e);
		
		$exceptionType = false;
		
		if (preg_match('#^Mozg_Exception_(.+)$#is', $class, $matches))
		{
			$exceptionType = $matches[1];
		}
		
		if (!$exceptionType || !method_exists($this, 'Handle' .$exceptionType))
		{
			$exceptionType = 'Default';
		}
		
		$this->{'Handle' .$exceptionType}($e);
	}
	
	/**
	 *
	 * clean all output buffers to clearly display errors
	 */
	protected function CleanBuffers()
	{
		while (ob_get_level())
		{
			ob_end_clean();
		}
	}
	
	protected function HandleDefault(Exception $e)
	{
		echo $e;
	}
	
    protected function GetTpl($name = '')
    {
    	foreach ($this->_detector as $component)
    	{
    		try
    		{
    			return Mozg::Tpl($name, $component[0], $component[1]);
    		}
    		catch (Exception $e)
    		{
    			
    		}
    	}

    	throw new Mozg_Exception_NotFound(Mozg_Lang::_('Template ' .$name. ' not found in %s', get_class($this)));
    }
}